﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    // Class for intercepting low level Windows mouse hooks.
    class MonitorMouse : IMonitor
    {
        Tuple<int, int> oldPosition;
        Tuple<int, int> newPosition;
        // Internal callback processing function
        private delegate IntPtr MouseHookHandler(int nCode, IntPtr wParam, IntPtr lParam);
        private MouseHookHandler hookHandler;
        
        // Function to be called when defined even occurs
        public delegate void MouseHookCallback(MSLLHOOKSTRUCT mouseStruct);

        // Low level mouse hook's ID
        private IntPtr hookID = IntPtr.Zero;
        
        // Dictionary to store coordinates and action
        private static Dictionary<MSLLHOOKSTRUCT, string> clicks;

        // Initialize low level mouse hook anddictionary taht stores them
        public MonitorMouse()
        {
            hookHandler = HookFunc;
            hookID = SetHook(hookHandler);
            clicks = new Dictionary<MSLLHOOKSTRUCT, string>();
        }

        // Remove low level mouse hook
        public string DisposeHook()
        {
            UnhookWindowsHookEx(hookID);

            StringBuilder coordinates = new StringBuilder();

            double width = Screen.PrimaryScreen.Bounds.Width;
            double height = Screen.PrimaryScreen.Bounds.Height;

            foreach (MSLLHOOKSTRUCT click in clicks.Keys)
            {
                coordinates.Append("(" + click.pt.x + ", " + click.pt.y + ") " + clicks[click] + " ");
            }
            return coordinates.ToString();

        }

        // Sets hook and assigns its ID for tracking
        private IntPtr SetHook(MouseHookHandler proc)
        {
            using (ProcessModule module = Process.GetCurrentProcess().MainModule)
                return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(module.ModuleName), 0);
        }

        // Callback function
        private IntPtr HookFunc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            // parse system messages
            if (nCode >= 0)
            {
                if (MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
                {
                        MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                        clicks.Add(hookStruct, "WM_LBUTTONDOWN");
                }
                if (MouseMessages.WM_LBUTTONUP == (MouseMessages)wParam)
                {
                        MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                        // clicks.Add(hookStruct, "WM_LBUTTONUP");
                }
                if (MouseMessages.WM_RBUTTONDOWN == (MouseMessages)wParam)
                {
                        MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                        clicks.Add(hookStruct, "WM_RBUTTONDOWN");
                }
                if (MouseMessages.WM_RBUTTONUP == (MouseMessages)wParam)
                {
                        MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                        // clicks.Add(hookStruct, "WM_RBUTTONUP");
                }
                if (MouseMessages.WM_MOUSEMOVE == (MouseMessages)wParam)
                {
                        MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                        //clicks.Add(hookStruct, "WM_MOUSEMOVE");
                }
                if (MouseMessages.WM_MOUSEWHEEL == (MouseMessages)wParam)
                {
                        MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                        clicks.Add(hookStruct, "WM_MOUSEWHEEL");
                }
                if (MouseMessages.WM_LBUTTONDBLCLK == (MouseMessages)wParam)
                {
                        MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                        clicks.Add(hookStruct, "WM_LBUTTONDBLCLK");
                }
                if (MouseMessages.WM_MBUTTONDOWN == (MouseMessages)wParam)
                {
                        MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                        clicks.Add(hookStruct, "WM_MBUTTONDOWN");
                }
                if (MouseMessages.WM_MBUTTONUP == (MouseMessages)wParam)
                {
                    MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                    //clicks.Add(hookStruct, "WM_MBUTTONUP");
                }
            }
            return CallNextHookEx(hookID, nCode, wParam, lParam);
        }

        #region WinAPI
        private const int WH_MOUSE_LL = 14;

        private enum MouseMessages
        {
            WM_LBUTTONDOWN = 0x0201,
            WM_LBUTTONUP = 0x0202,
            WM_MOUSEMOVE = 0x0200,
            WM_MOUSEWHEEL = 0x020A,
            WM_RBUTTONDOWN = 0x0204,
            WM_RBUTTONUP = 0x0205,
            WM_LBUTTONDBLCLK = 0x0203,
            WM_MBUTTONDOWN = 0x0207,
            WM_MBUTTONUP = 0x0208
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int x;
            public int y;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MSLLHOOKSTRUCT
        {
            public POINT pt;
            public uint mouseData;
            public uint flags;
            public uint time;
            public IntPtr dwExtraInfo;
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            MouseHookHandler lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
    }
        #endregion
}
